package com.crm.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.crm.entity.SysUser;
import com.crm.model.JsonMessage;
import com.crm.security.util.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {


    public JWTLoginFilter(AuthenticationManager authManager) {
        setAuthenticationManager(authManager);
        super.setFilterProcessesUrl("/user/login");
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        try {
            SysUser sysUser= new ObjectMapper().readValue(request.getInputStream(),SysUser.class);

           // User user=new User(sysUser.getLoginName(),sysUser.getLoginPass(),new ArrayList<>());
            return this.getAuthenticationManager().authenticate(
                    new UsernamePasswordAuthenticationToken(
                            sysUser.getLoginName(),sysUser.getLoginPass()
                    )
            );

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


    }


    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException {


        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json; charset=utf-8");
        AuthUserDetail detail= (AuthUserDetail) auth.getPrincipal();
        String token = JwtUtil.createJWT(detail);
        res.addHeader(JwtUtil.HEADER_STRING, JwtUtil.TOKEN_PREFIX + token);
        JsonMessage message=new JsonMessage("登录成功",HttpServletResponse.SC_OK,true);
        message.setData(JwtUtil.TOKEN_PREFIX + token);
        res.getWriter().write(new ObjectMapper().writeValueAsString(message));
        //chain.doFilter(req,res);
        //super.doFilter(req,res,chain);
    }
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {


        JsonMessage message=new JsonMessage("用户名或密码错误",HttpServletResponse.SC_OK,false);
        message.setData("用户名或密码有误！");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(message));
        //response.getWriter().write("authentication failed, reason: " + failed.getMessage());
    }

}

